import { useRequest, useTitle } from "ahooks"
import React, { FC, useEffect } from "react"
import { Link, useNavigate } from "react-router-dom"
import { Typography, Space, Form, Input, Button, Checkbox, message } from "antd"
import { UserOutlined } from "@ant-design/icons"
import styles from "./Login.module.scss"
import { MANGE_INDEX_PATHNAME, REGISTER_PATHNAME } from "../router"
import { loginService } from "../services/user"
import { setToken } from "../utils/user-token"

const { Title } = Typography

const USERNAME_KEY = "USERNAME"
const PASSWORD_KEY = "PASSWORD"

// 保存账号密码缓存
function rememberUser(username: string, password: string) {
    localStorage.setItem(USERNAME_KEY, username)
    localStorage.setItem(PASSWORD_KEY, password)
}

// 删除缓存的账号密码
function deleteUserFromStorage() {
    localStorage.removeItem(USERNAME_KEY)
    localStorage.removeItem(PASSWORD_KEY)
}

// 获取账号密码的缓存
function getUserInfoFromStorage() {
    return {
        username: localStorage.getItem(USERNAME_KEY),
        password: localStorage.getItem(PASSWORD_KEY)
    }
}

const Login: FC = () => {
    useTitle("问卷星途 - 登录")

    const nav = useNavigate()

    // 表单实例
    const [form] = Form.useForm() // 第三方hook

    useEffect(() => {
        const { username, password } = getUserInfoFromStorage()
        // 给表单设置值  —————— 难点（如何将值设置到表单中）
        form.setFieldsValue({ username, password })
    }, [])

    const { run: handleLogin } = useRequest(
        async (username: string, password: string) => {
            const data = await loginService(username, password)
            return data
        },
        {
            manual: true,
            onSuccess(result) {
                const { token = "" } = result
                // 存储token
                setToken(token)
                message.success("登录成功")
                nav(MANGE_INDEX_PATHNAME)
            }
        }
    )

    const onFinish = (values: any) => {
        // console.log(values)
        const { username, password, remember } = values || {}
        handleLogin(username, password)

        if (remember) {
            rememberUser(username, password)
        } else {
            deleteUserFromStorage()
        }
    }

    return (
        <div className={styles.container}>
            <div>
                <Space>
                    <Title level={2}>
                        <UserOutlined />
                    </Title>
                    <Title level={2}>用户登录</Title>
                </Space>
            </div>
            <div>
                <Form
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: 400 }}
                    initialValues={{ remember: true }}
                    form={form}
                    onFinish={onFinish}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[
                            { required: true, message: "请输入用户名" },
                            {
                                type: "string",
                                min: 5,
                                max: 20,
                                message: "字符长度在 5-20 之间"
                            },
                            // 正则表达式
                            {
                                pattern: /^\w+$/,
                                message: "只能是字母数字下划线"
                            }
                        ]}
                    >
                        <Input autoComplete="username" />
                    </Form.Item>

                    <Form.Item label="密码" name="password" rules={[{ required: true, message: "请输入密码" }]}>
                        <Input.Password autoComplete="current-password" />
                    </Form.Item>
                    <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 5, span: 15 }}>
                        <Checkbox>记住密码</Checkbox>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 9, span: 15 }}>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                登录
                            </Button>
                            <Link to={REGISTER_PATHNAME}>注册新用户</Link>
                        </Space>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}

export default Login
